import axios from 'axios'
import { Toast, Dialog } from 'vant'
import router from './../router'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'

export const BASE_API =  `${process.env.VUE_APP_BASE_ROUTER}api`

const Http = (url, methods, data, config, needUrl) => {
  let operateConfig = {
    url,
    method: methods || 'post',
    data,
    params: data,
    config
  }

  // 不同请求 防止除get外的请求，参数拼接 导致url过长
  if (methods === 'get') {
    delete operateConfig.data
  } else if (!needUrl) {
    delete operateConfig.params
  }
  return axios(operateConfig)
}

axios.interceptors.request.use(
  (config) => {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
      duration: 0,
      className: 'loading-toast-class',
    })
    let token = localStorage.getItem(process.env.VUE_APP_TOKEN_NAME)
    if (token) {
      config.headers['Authorization'] = `bearer  ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(res => {
    Toast.clear()
    if (res.data.succ) {
      return Promise.resolve(res.data)
    } else if (res.data?.imagePath) {
      return Promise.resolve(res.data?.imagePath)
    } else {
      Toast(res.data.msg)
      // return Promise.reject(res.data)
    }
  },
  error => {
    Toast.clear()
    if (error?.response?.status === 401) {
      const userStore = useUserStore()
      const { userInfo } = storeToRefs(userStore)
      Dialog.alert({
        message: '登录过期，请重新登录',
      }).then(() => {
        router.replace({
          name: 'bind',
          query: {
            id: userInfo.value.qaaId
          }
        })
      })
    } else {
      Toast(error?.response?.data?.msg || '服务器错误，请稍后重试')
      return Promise.reject(error)
    }
  }
)

export default Http
